<template>
  <div style="padding: 20px;">
    <div class="item">
      <div class="name">作业名称 <span class="red">*</span>:</div>
      <el-input style="width: 780px;" placeholder="请输入作业名称" v-model="taskName"></el-input>
    </div>
    <div class="source">
      <div class="header">
        <div class="title">
          <i class="el-icon-document">源文件</i>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注意：本地文件上传会有同名文件覆盖风险</span>
          <!-- <span class="priview-span" aria-describedby="tooltip" data-toggle="tooltip" data-placement="right" title='' data-html="true" data-original-title="<div class='t1' style='width:600px;text-align:left;'>本地文件不能包含中文字符，且大小最大支持到2GB<br/>
                             文件名中支持正则表达式写法以匹配多个文件，文件名前需加【REGEX:】前缀。<br/>如：/tmp/REGEX:abc[A-Z,a-z,0-9,+,-,_]{0,50}.tgz<br/>如需分发文件目录，文件名请以‘/’结束<br/></div>">
						<i class="el-icon-question"></i>
            <div class="tooltip right fade in" role="tooltip" id="tooltip" style="top: 53px;left: 472px;display: block;"></div>
					</span> -->
          <div style="float: right !important;">
            <!-- <input type="file" id="files" style="display: none;" onchange="import();"/> -->
            <!-- <el-button id="import" type="info" icon="el-icon-upload2" @click="chooseLocalDoc">添加本地文件</el-button> -->
            <tool-simple-upload style="float: right !important;margin-left:10px;" :action="action" :multiple="true" :on-success="onSuccess"></tool-simple-upload>
            <el-button type="info" icon="el-icon-upload" @click="chooseRemoteDoc">添加服务器文件</el-button>
          </div>
        </div>
      </div>
      <el-table
        :data.sync="results"
        style="width: 100%;text-align: center;"
        empty-text="请添加源文件!">
        <el-table-column
          header-align="center"
          prop="docList"
          label="文件列表"
          width="200">
        </el-table-column>
        <el-table-column
          header-align="center"
          prop="address"
          label="服务器地址"
          width="200">
        </el-table-column>
        <el-table-column
          header-align="center"
          prop="root"
          label="执行账户"
          width="150">
        </el-table-column>
        <el-table-column
          header-align="center"
          label="所有操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="source">
      <div class="header">
        <div class="title">
          <i class="el-icon-printer">目标文件</i>
        </div>
      </div>
      <div class="item" style="margin-left: 20px;">
        <div class="name">目标路径 <span class="red">*</span>:</div>
        <el-input style="width: 720px;" placeholder="请填写分发路径" v-model="goalAddress"></el-input>
      </div>
      <div class="item" style="margin-left: 20px;">
        <div class="name">执行账户 <span class="red">*</span>:</div>
        <el-select v-model="rootName" filterable clearable style="width: 680px;">
          <el-option v-for="item in rootNames" :key="item.id" :label="item.account" :value="item.account"></el-option>
        </el-select>
        <div class="add" @click="addRole">
          <i class="el-icon-plus"></i>
        </div>
      </div>
      <div class="add-role" v-show="showAddRole">
        <div class="item" style="margin-left: 20px;">
          <div class="name">账户名称 <span class="red">*</span>:</div>
          <el-input style="width: 300px;" placeholder="此账户必须在目标服务器上存在" v-model="inputRole"></el-input>
          <el-button type="primary" style="margin-left: 20px;" @click="newRole">登记账户</el-button>
          <!-- <div class="help-info">
            <i class="el-icon-question"></i>
          </div> -->
        </div>
        <p class="add-error" v-if="addError">帐号名称不合法，应该以英文字母和阿拉伯数字下划线为命名长度不超过32个字符!</p>
      </div>
      <div class="item" style="margin-left: 20px;margin-bottom: 10px;">
        <div class="name">目标机器 <span class="red">*</span>:</div>
        <el-button type="primary" icon="el-icon-upload" @click="chooseServer">选择服务器</el-button>
      </div>
      <tool-choose-service :machines="machines" @close="close" v-on:choosed="serverList"></tool-choose-service>
      <div class="add-role" style="background: #ffffff;border: 1px solid #DDDDDD;padding: 10px;" v-show="showChoosed">
        <el-table
          :data="choosedServer"
          style="width: 100%;text-align: center;"
          empty-text="请添加源文件!">
          <el-table-column
            header-align="center"
            prop="host_name"
            label="平台名称"
            width="200">
          </el-table-column>
          <el-table-column
            header-align="center"
            prop="ip"
            label="IP/分组"
            width="200">
          </el-table-column>
          <el-table-column
            header-align="center"
            prop="status"
            label="状态"
            width="150">
              <template slot-scope="scope">
                  <span v-if="scope.row.status === 1" style="color: green;">Running</span>
                  <span v-else style="color: red;">Stop</span>
              </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="deleteChoosed(scope.$index, scope.row)">删除</el-button>
              </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="repline"></div>
    <el-button type="success" style="margin-left: 50%;transform: translate(-50%,0);" @click="executeIssue">开始分发</el-button>
    <el-dialog
      title="提示"
      :visible.sync="warningInfo"
      width="30%">
      <div><span class="red">*</span> 为必填项,请完善信息!</div>
    </el-dialog>
  </div>
</template>

<script>
  import services from '../../components/ChooseServer/index'
  import upload from '../../components/simpleUpload/index'
  import { serverList, AccountList, AddAccount, FileDistribute, DeleteUploadFile } from '../../api/configure'

  export default {
    name: 'fast-issue',
    components: {
      'tool-choose-service': services,
      'tool-simple-upload': upload
    },
    data() {
      return {
        taskName: '',
        results: [],
        action: 'http://192.168.25.197:8765/file/upload',
        machines: [],
        result: '',
        goalAddress: '',
        rootName: '',
        rootNames: [],
        showAddRole: false,
        inputRole: '',
        addError: false,
        showChoosed: false,
        choosedServer: [],
        warningInfo: false,
        disInfo: null,
        sourceType: 0
      }
    },
    watch: {
      choosedServer: function(val) {
        if (val.length !== 0) {
          this.showChoosed = true
        }
      },
      disInfo: function(val) {
        if (val !== null) {
          FileDistribute(val).then(res => {
            if (res.code === 200) {
              this.$router.push({ path: '/task/issue-run', query: { id: res.data }})
            }
          })
        }
      }
    },
    created() {
      AccountList().then(res => {
        if (res.code === 200) {
          this.rootNames = res.data
          this.rootName = this.rootNames[0].account
        }
      }).catch(err => {
        console.log(err)
        this.rootNames = []
        this.$notify({
          title: '失败',
          message: '获取失败',
          type: 'warning',
          duration: 2000
        })
      })
    },
    methods: {
      chooseLocalDoc() {
        document.getElementById('files').click()
      },
      addRole() {
        this.showAddRole = !this.showAddRole
      },
      newRole() {
        var str = this.inputRole
        if (str === '') {
          this.addError = true
          return
        }
        if (str.length > 32) {
          this.addError = true
          return
        }
        for (var i = 0; i < str.length; i++) {
          if (str.charAt(i) < 'A' || (str.charAt(i) > 'Z' && str.charAt(i) < 'a' && str.charAt(i) !== '_') || str.charAt(i) > 'z') {
            this.addError = true
            return
          }
        }
        var obj = {}
        obj.account = str
        AddAccount(obj).then(res => {
          if (res.code === 200) {
            AccountList().then(res => {
              if (res.code === 200) {
                this.rootNames = res.data
              }
            }).catch(err => {
              console.log(err)
              this.rootNames = []
              this.$notify({
                title: '失败',
                message: '获取失败',
                type: 'warning',
                duration: 2000
              })
            })
            this.rootName = str
          }
        }).catch(err => {
          console.log(err)
          this.$notify({
            title: '失败',
            message: '获取失败',
            type: 'warning',
            duration: 2000
          })
        })
      },
      import() {
        var selectedFile = document.getElementById('files').files[0]// 获取读取的File对象
        // var name = selectedFile.name// 读取选中文件的文件名
        // var size = selectedFile.size// 读取选中文件的大小
        // console.log("文件名:" + name + "大小：" + size);

        var reader = new FileReader()// 这里是核心！！！读取操作就是由它完成的。
        reader.readAsText(selectedFile)// 读取文件的内容

        reader.onload = function() {
          // console.log(this.result);// 当读取完成之后会回调这个函数，然后此时文件的内容存储到了result中。直接操作即可。
        }
      },
      chooseRemoteDoc() {

      },
      chooseServer() {
        serverList().then(res => {
          if (res.code === 200) {
            this.machines = res.data
          }
        }).catch(err => {
          console.log(err)
          this.machines = []
          this.$notify({
            title: '失败',
            message: '获取失败',
            type: 'warning',
            duration: 2000
          })
        })
      },
      close() {
        this.machines = []
      },
      serverList(multipleSelection) {
        this.choosedServer = multipleSelection
      },
      onSuccess(val, file) {
        var obj = {}
        obj.docList = file.name
        this.results.push(obj)
        this.sourceType = 0
      },
      handleDelete(index, row) {
        var params = {}
        params.filename = row.docList
        DeleteUploadFile(params).then(res => {
          if (res.code === 200) {
            for (var i = 0; i < this.results.length; i++) {
              if (this.results[i].docList === row.docList) {
                this.results.splice(i, 1)
              }
            }
          }
        }).catch(err => {
          console.log(err)
          this.$notify({
            title: '失败',
            message: '删除失败',
            type: 'warning',
            duration: 2000
          })
        })
      },
      deleteChoosed(index, row) {
        for (var i = 0; i < this.choosedServer.length; i++) {
          if (this.choosedServer[i].id === row.id) {
            this.choosedServer.splice(i, 1)
            if (this.choosedServer.length === 0) {
              this.showChoosed = false
            }
          }
        }
      },
      executeIssue() {
        if (this.taskName === '' || this.results.length === 0 || this.goalAddress === '' || this.rootName === '' || this.choosedServer.length === 0) {
          this.warningInfo = true
          return
        }
        var obj = {}
        obj.name = this.taskName
        obj.files = this.results[0].docList
        for (let i = 1; i < this.results.length; i++) {
          obj.files += '\n' + this.results[i].docList
        }
        obj.fileTargetPath = this.goalAddress
        obj.targetIpHosts = this.choosedServer[0].ip
        for (let i = 1; i < this.choosedServer.length; i++) {
          obj.targetIpHosts += '\n' + this.choosedServer[i].ip
        }
        obj.targetAccount = this.rootName
        obj.type = this.sourceType
        this.disInfo = obj
      }
    }
  }
</script>

<style lang="scss" scoped>
  .repline{
    margin: 20px 0;
    margin-left: 170px;
    width: 780px;
    background: rgba(00, 00, 00, .2);
    height: 1px;
  }
  .red {
    color: red;
  }
  .name {
    font-size: 16px;
    line-height: 36px;
    margin-right: 20px;
  }
  .item {
    position: relative;
    margin-top: 10px;
    margin-left: 120px;
    display: box;
    display: -webkit-box;
    .add {
      width: 36px;
      height: 36px;
      margin-left: 2px;
      border: 1px solid rgba(00,00,00,.3);
      .el-icon-plus {
        margin-left: 50%;
        margin-top: 50%;
        transform: translate(-50%,-50%);
        -webkit-transform: translate(-50%,-50%);
        color: rgba(00,00,00,.3);
      }
    }
    // .help-info {
    //   margin-left: 15px;
    //   margin-top: 10px;
    //   color: rgba(00,00,00,.6);
    // }
  }
  .add-role {
    width: 640px;
    height: auto;
    margin-left: 120px;
    margin-top: 10px;
    padding-top: 20px;
    padding-bottom: 20px;
    background: rgba(00, 00, 00, .3);
  }
  .add-error {
    width: 300px;
    color: red;
    margin-left: 120px;
    margin-top: 10px;
    line-height: 18px;
    font-size: 14px;
  }
  .source {
    width: 880px;
    border: 1px solid #DDDDDD;
    min-height: 80px;
    margin-left: 120px;
    margin-top: 20px;
    padding: 0 15px;
    .header {
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
      font-size: 13px;
      height: 54px;
      .title {
        line-height: 54px;
        font-size: 15px;
        font-weight: 700;
        // .priview-span {
        //   margin-top: 8px;
        //   margin-left: 5px;
        //   display: inline-block;
        //   cursor: pointer
        // }
      }
    }
  }
</style>
